__author__ = 'st316'
'''
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity,
it should invalidate the least recently used item before inserting a new item.
'''

import collections


class LRUCache:
    # @param capacity, an integer
    def __init__(self, capacity):
        self.cache = collections.OrderedDict()
        self.capacity = capacity
        self.num = 0

    # @return an integer
    def get(self, key):
        try:
            value = self.cache[key]
            del self.cache[key]
            self.cache[key] = value
            return value
        except KeyError:
            return -1

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        try:
            del self.cache[key]
            self.cache[key] = value
            return
        except KeyError:
            if self.num == self.capacity:
                self.cache.popitem(last=False)
                self.num -= 1
            self.cache[key] = value
            self.num += 1

if __name__ == '__main__':
    pass